<template>
  <n-tabs ref="tabsRef" type="line" v-model:value="currentTab">
    <n-tab @click="emits('choose')" v-for="(item,index) in tabs" :name="item" :key="index">
      {{ item }}
    </n-tab>
    <template #prefix>
      <n-button @mousedown="handleSwitch(-1)" v-if="isSwitchButtonShow" text>
        <n-icon size="18">
          <icon icon="mingcute:left-fill"></icon>
        </n-icon>
      </n-button>
    </template>
    <template #suffix>
      <n-button @mousedown="handleSwitch(1)" v-if="isSwitchButtonShow" text>
        <n-button text>
          <n-icon size="18">
            <icon icon="mingcute:right-fill"></icon>
          </n-icon>
        </n-button>
      </n-button>
    </template>
  </n-tabs>
</template>

<script setup lang="ts">


import {Icon} from "@iconify/vue";
import {computed, onMounted, PropType, ref, watch} from "vue";
import {useWindowSize, useMousePressed} from '@vueuse/core'

const isSwitchButtonShow = ref(false)
const tabsRef = ref()
const {width} = useWindowSize()
const {pressed} = useMousePressed()
const props = defineProps({
  tabs: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  tab: {
    type: String,
    default: ''
  },
  value: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update:tab', 'choose'])
const currentTab = computed(
    {
      set(val: string) {
        emits('update:tab', val)
      },
      get() {
        return props.tab
      }
    }
)

const handleSwitch = (val: number) => {
  let timer = setInterval(() => {
    tabsRef.value.xScrollInstRef.$el.scrollLeft += 50 * val
    if (!pressed.value) {
      clearInterval(timer)
    }
  }, 50)
}

const getWidth = () => {
  if (tabsRef.value) {
    const wrapper: HTMLElement = tabsRef.value.$el.getElementsByClassName('n-tabs-wrapper')[0] as HTMLElement;
    const s = wrapper.offsetWidth;
    const f = wrapper.parentElement?.offsetWidth;
    isSwitchButtonShow.value = s >= (f || 0);
  }
};

watch(width, getWidth);
onMounted(() => {
  setTimeout(() => {
    getWidth()
  }, 500)
});


</script>

<style scoped>

</style>